package com.yan.system.controller;

import com.yan.baseController.BaseController;
import com.yan.common.annotation.LogAnntation;
import com.yan.system.bean.Menu;
import com.yan.system.bean.Tree;
import com.yan.system.service.FileService;
import com.yan.system.service.MenuService;
import com.yan.utils.AjaxResult;
import com.yan.utils.FileDO;
import com.yan.utils.MD5Utils;
import com.yan.utils.ShiroUtils;
import groovy.util.logging.Log;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by yanl_ on 2018/4/4.
 */

@Controller
public class LoginController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MenuService menuService;

    @Autowired
    FileService fileService;

    @GetMapping({"/", ""})
    String welcome(Model model) {
        return "redirect:/blog";
    }


    /**
     * SELECT DISTINCT
     m.menu_id,
     parent_id,
     NAME,
     url,
     perms,
     `type`,
     icon,
     order_num,
     gmt_create,
     gmt_modified
     FROM
     sys_menu m
     LEFT JOIN sys_role_menu rm ON m.menu_id = rm.menu_id
     LEFT JOIN sys_user_role ur ON rm.role_id = ur.role_id
     WHERE
     ur.user_id = 1
     AND m.type IN (0, 1)
     ORDER BY
     m.order_num
     *
     * @param model
     * @return
     */

    @LogAnntation("请求访问主页")
    @GetMapping({"/index"})
    String index(Model model) {
        List<Tree<Menu>> menus = menuService.listMenuTree(getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        FileDO fileDO = fileService.get(getUser().getPicId());
        if (fileDO != null && fileDO.getUrl() != null) {
            if (fileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", fileDO.getUrl());
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg");
            }
        } else {
            model.addAttribute("picUrl", "/img/photo_s.jpg");
        }
        model.addAttribute("username", getUser().getUsername());
        return "index_v1";
    }

    @GetMapping("/login")
    String login() {
        return "login";
    }

    @LogAnntation("登陆")
    @PostMapping("/login")
    @ResponseBody
    AjaxResult ajaxLogin(String username, String password) {

        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return AjaxResult.ok();
            //   } //catch (UnknownAccountException e) {
//            return AjaxResult.error("username error");
            // }
//        catch (IncorrectCredentialsException e) {
//            return AjaxResult.error(" password error");
        } catch (AuthenticationException e) {
            return AjaxResult.error("用户或密码错误");
        }
    }

    @GetMapping("/logout")
    String logout() {
        ShiroUtils.logout();
        return "redirect:/login";
    }

    @GetMapping("/main")
    String main() {
        return "main";
    }

}
